// +----------------------------------------------------------------------


// +----------------------------------------------------------------------
export default {
    /**
	 * 生成唯一ID
	 */
    getUuid(){
		var d = new Date().getTime();
		var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
			var r = (d + Math.random()*16)%16 | 0;
			d = Math.floor(d/16);
			return (c=='x' ? r : (r&0x3|0x8)).toString(16);
		});
		return uuid;
    },
	/**
	 * 获取当前时间戳
	 */
	time() {
		return Math.round(new Date());
	},
	/**
	 * 字符串转时间戳
	 * @param {Object} expiresTime
	 */
	strTotime(expiresTime){
		let expires_time = expiresTime.substring(0, 19);
		expires_time = expires_time.replace(/-/g, '/');
		return Math.round(new Date(expires_time).getTime());
	},

   /**
	* 对像排序
	* @param {Object} obj 对像 {name: "zhangsan", age: 8, ace: 5, nbme: "lisi"}
	* @param {Object} type asc 降序 desc 倒序
	*/
	 objKeySort(obj, type){
	  type = type.toLowerCase();
	  if (type == 'asc') var newkey = Object.keys(obj).sort();
	  else if (type == 'desc') var newkey = Object.keys(obj).sort().reverse();
	  else var newkey = Object.keys(obj).sort();
	  var newObj = {};
	  for (var i = 0; i < newkey.length; i++) {
	    newObj[newkey[i]] = obj[newkey[i]];
	  }
	  return newObj;
	},

	 /**
	  * 格式化金额
	  * @param {Object} s   数字金额
	  * @param {Object} n   保留的小数位数
	  * @param {Object} y   是否使用以豆号为分隔
	  */
	formatCurrency(s,n,y) {
	  if (!arguments[1]) n = 2;
	  if (!arguments[2]) y = false;
	  n = n > 0 && n <= 20 ? n : 2;
	  var f = s < 0 ? "-" : "";
	   s = parseFloat((Math.abs(s) + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
	  if (y) {
	    var l = s.split(".")[0].split("").reverse(),
	      r = s.split(".")[1];
	    t = "";
	    for (i = 0; i < l.length; i++) {
	      t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
	    }
	    return f + t.split("").reverse().join("") + "." + r.substring(0, 2);
	  } else {
	    return s;
	  }  
	},

	/**
	 * 验证邮箱
	 * @param {Object} email
	 */
    isEmail(email){
		   var myreg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
		   if(!myreg.test(email)){
				return false;
		  }
		  return true;
	},
	
	/**
	 * 只能输入英文、数字、下横线、中横线
	 * @param {Object} value
	 */
	isNumAbcs(value){
	    var reg = /^[\.\@A-Za-z0-9-_\u554A-\u9C52]+$/;
	     if(reg.test(value)){
		     return true;
		 }else{
		     return false;
		 }
	},
	
	/**
	 * 只能输入数字
	 * @param {Object} value
	 */
	isNum(value){
	    var reg = /^\d+$/;
	     if(reg.test(value)){
		     return true;
		 }else{
		     return false;
		 }
	},
	
	/**
	 * 提取字符串中的数字
	 * @param {Object} text
	 */
	getNum(text){
		var value = text.replace(/[^0-9\.]/ig,""); 
		return value;
	},
	
	/**
	 * php时间戳转换js日期格式
	 * @param {Object} time
	 */
	setDate(time){
	  return new Date(parseInt(time) * 1000).toLocaleString().replace(/:\d{1,2}$/, ' ');
	},
	
	/**
	 * 对像数组按指定
	 * @param {Object} key
	 * @param {Object} desc
	 */
	keysrt(key, desc) {
	  return function (a, b) {
	    return desc ? ~~(a[key] < b[key]) : ~~(a[key] > b[key]);
	  }
	},
	
	/**
	 * 图片自动适应大小
	 * @param {Object} e
	 */
	imageUtil(e) {
	  var imageSize = {};
	  var originalWidth = e.detail.width;//图片原始宽 
	  var originalHeight = e.detail.height;//图片原始高 
	  var originalScale = originalHeight / originalWidth;//图片高宽比 
	  console.log('originalWidth: ' + originalWidth)
	  console.log('originalHeight: ' + originalHeight)
	  //获取屏幕宽高 
	  uni.getSystemInfo({
	    success:(res)=>{
	      var windowWidth = res.windowWidth;
	      var windowHeight = res.windowHeight;
	      var windowscale = windowHeight / windowWidth;//屏幕高宽比 
	      console.log('windowWidth: ' + windowWidth)
	      console.log('windowHeight: ' + windowHeight)
	      if (originalScale < windowscale) {//图片高宽比小于屏幕高宽比 
	        //图片缩放后的宽为屏幕宽 
	        imageSize.imageWidth = windowWidth;
	        imageSize.imageHeight = (windowWidth * originalHeight) / originalWidth;
	      } else {//图片高宽比大于屏幕高宽比 
	        //图片缩放后的高为屏幕高 
	        imageSize.imageHeight = windowHeight;
	        imageSize.imageWidth = (windowHeight * originalWidth) / originalHeight;
	      }
	
	    }
	  })
	  //console.log('缩放后的宽: ' + imageSize.imageWidth)
	  //console.log('缩放后的高: ' + imageSize.imageHeight)
	  return imageSize;
	} ,
	
   /**
	* 对像数组
	* @param {Object} obj   对像数组
	* @param {Object} key   要排序的KEY值
	* @param {Object} type  true高到底，false底到高
	*/
	objSort(obj, key, type) {
	  return obj.sort(keysrt(key, type));
	},
	
	/**
	 * 验证身份证号码
	 * @param {Object} code
	 */
	checkID(code){
	  var city = {
	    11: "北京",
	    12: "天津",
	    13: "河北",
	    14: "山西",
	    15: "内蒙古",
	    21: "辽宁",
	    22: "吉林",
	    23: "黑龙江 ",
	    31: "上海",
	    32: "江苏",
	    33: "浙江",
	    34: "安徽",
	    35: "福建",
	    36: "江西",
	    37: "山东",
	    41: "河南",
	    42: "湖北 ",
	    43: "湖南",
	    44: "广东",
	    45: "广西",
	    46: "海南",
	    50: "重庆",
	    51: "四川",
	    52: "贵州",
	    53: "云南",
	    54: "西藏 ",
	    61: "陕西",
	    62: "甘肃",
	    63: "青海",
	    64: "宁夏",
	    65: "新疆",
	    71: "台湾",
	    81: "香港",
	    82: "澳门",
	    91: "国外 "
	  };
	  var tip = "";
	  var pass = true;
	  if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[12])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)) {
	    tip = "身份证号格式错误";
	    pass = false;
	  }else if (!city[code.substr(0, 2)]) {
	    tip = "地址编码错误";
	    pass = false;
	  }else {
	    //18位身份证需要验证最后一位校验位
	    if (code.length == 18) {
	      code = code.split('');
	      //∑(ai×Wi)(mod 11)
	      //加权因子
	      var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
	      //校验位
	      var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
	      var sum = 0;
	      var ai = 0;
	      var wi = 0;
	      for (var i = 0; i < 17; i++) {
	        ai = code[i];
	        wi = factor[i];
	        sum += ai * wi;
	      }
	      var last = parity[sum % 11];
	      if (parity[sum % 11] != code[17]) {
	        tip = "校验位错误";
	        pass = false;
	      }
	    }
	  }
	  //if (!pass) alert(tip);
	  return pass;    
	},
	
	/**
	 * 验证手机号
	 * @param {Object} phone
	 */
	checkPhone(phone){
	  if (!phone) return false;
	  if (!(/^1(3|4|5|6|7|8|9)\d{9}$/.test(phone))) {
	    return false;
	  }
	  return true; 
	},

	 /**
	  * 将中文转为
	  * @param {Object} inputStr
	  */
	stringToUtf8(inputStr) { 
		var outputStr = "";
		for (var i = 0; i < inputStr.length; i++) {
		  var temp = inputStr.charCodeAt(i);
		  //0xxxxxxx
		  if (temp < 128) {
			outputStr += String.fromCharCode(temp);
		  }
		  //110xxxxx 10xxxxxx
		  else if (temp < 2048) {
			outputStr += String.fromCharCode((temp >> 6) | 192);
			outputStr += String.fromCharCode((temp & 63) | 128);
		  }
		  //1110xxxx 10xxxxxx 10xxxxxx
		  else if (temp < 65536) {
			outputStr += String.fromCharCode((temp >> 12) | 224);
			outputStr += String.fromCharCode(((temp >> 6) & 63) | 128);
			outputStr += String.fromCharCode((temp & 63) | 128);
		  }
		  //11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
		  else {
			outputStr += String.fromCharCode((temp >> 18) | 240);
			outputStr += String.fromCharCode(((temp >> 12) & 63) | 128);
			outputStr += String.fromCharCode(((temp >> 6) & 63) | 128);
			outputStr += String.fromCharCode((temp & 63) | 128);
		  }
		}
		return outputStr;
	},
	
   /**
	* 删除指定KDY数组对像 
	* @param {Object} obj 数组对你
	* @param {Object} key 删除指的KEY
	*/
	objDelete(obj, key) {
	  if (!isNaN(key)) key = parseInt(key);
	  var newObj = {};
	  for (var i in obj) {
	    if (i != key) newObj[i] = obj[i];
	  }
	  return newObj;
	},
	
	/**
	 * 删除对像数组列表
	 * @param {Object} list     列表数组   [0:{id:3,name:李四}]
	 * @param {Object} diField  如 'id'
	 * @param {Object} idValue  对比键值，支持批删除 1,2,3,4,5,6,7
	 */
	delObjLIst(list, diField, idValue) {
	  if (!list || !diField) return [];
	  idValue = idValue.toString();
	  if (idValue.indexOf(',') == -1) idValue += ',0';
	  idValue = idValue.split(',');
	  var newAres = [];
	  var j = 0;
	  for (var i in list) {
	    var config = false;
	    for (var k = 0; k < idValue.length; k++) {
	      if (idValue[k] == list[i][diField]) {
	        config = true;
	        break;
	      }
	    }
	    if (!config) newAres[j++] = list[i];
	  }
	  return newAres;
	},
	
	/**
	 * 一维数组对像转二维数组对像
	 * @param {Object} obj  数组对像
	 * @param {Object} num  每个二维数组包含多少条数据
	 */
	twoObj(obj, num) {
	  if (!obj || !num) return {};
	  var newObj = {};
	  var j = 0;
	  var k = 0;
	  for (var i in obj) {
	    if (!newObj[j]) newObj[j] = {};
	    if (!newObj[j][k]) newObj[j][k] = {};
	    newObj[j][k] = obj[i];
	    k++;
	    if (k >= num) {
	      j++;
	      k = 0;
	    }
	  }
	  obj = null;
	  return newObj;
	},
	
	/**
	 * 字符串截取 str字符串；num截取长度；ellipsis 省略号
	 * @param {Object} str
	 * @param {Object} num
	 * @param {Object} ellipsis
	 */
	substr(str, num, ellipsis) {
	  ellipsis = arguments[2] ? arguments[2] : '...';
	  if (str.length > num) return str.substring(0, num) + ellipsis;
	  return str.substring(0, num);
	},
	/**
	 * 清除两边空格
	 * @param {Object} obj
	 */
	clearSpace(obj){
		if( typeof(obj) == "object"){
			for(let i in obj) if(obj[i]) obj[i]=obj[i].replace(/(^\s*)|(\s*$)/g, "");
			return obj;
		}else{
			if(obj) return obj.replace(/(^\s*)|(\s*$)/g, "");
			else return '';
		}
	},
	
	/**
	 * 时间截转换日期
	 * @param {Object} timestamp  时间截 10位和13位兼用
	 * @param {Object} format  格式： Y-m-d H:i:s
	 */
	timestampToDate(timestamp,format='Y-m-d H:i:s') {
	    if(!timestamp) return '';
	    if(format) format=format.toLowerCase();
	    let checkNUmber=(timestamp.toString()).length;
	    if(checkNUmber == 10) timestamp=timestamp*1000;
	    const date = new Date(timestamp);
	    const year = date.getFullYear();
	    const month = String(date.getMonth() + 1).padStart(2, '0');
	    const day = String(date.getDate()).padStart(2, '0');
	    const hours = String(date.getHours()).padStart(2, '0');
	    const minutes = String(date.getMinutes()).padStart(2, '0');
	    const seconds = String(date.getSeconds()).padStart(2, '0');
	    if(!format) return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
	    let string='';
	    format=format.replace('y',year);
	    format=format.replace('m',month);
	    format=format.replace('d',day);
	    format=format.replace('h',hours);
	    format=format.replace('i',minutes);
		format=format.replace('s',seconds);
		return format;
	},
	/**
	 * 时间截格式转换
	 * 今天 > 昨天 > 本周内 > 更早时间
	 */
	formatTimestamp:(timestamp)=>{
		const date = new Date(timestamp * 1000); // 转换为毫秒
		const now = new Date();
		// 获取今天凌晨时间戳（本地时区）
		const todayStart = new Date(now);
		todayStart.setHours(0, 0, 0, 0);
		const todayTimestamp = todayStart.getTime();
		// 获取昨天凌晨时间戳
		const yesterdayTimestamp = todayTimestamp - 86400000;
		// 获取本周一凌晨时间戳
		const mondayTimestamp = todayTimestamp - (now.getDay() === 0 ? 6 : now.getDay() - 1) * 86400000;
		// 格式化辅助函数
		const formatTime = (d) => {
			const hours = d.getHours().toString().padStart(2, '0');
			const minutes = d.getMinutes().toString().padStart(2, '0');
			return `${hours}:${minutes}`;
		};
		
		const formatDate = (d) => {
			const year = d.getFullYear();
			const month = (d.getMonth() + 1).toString().padStart(2, '0');
			const day = d.getDate().toString().padStart(2, '0');
			return `${year}-${month}-${day}`;
		};
		
		// 判断逻辑
		const inputTimestamp = date.getTime();
		
		if (inputTimestamp >= todayTimestamp) {
			return formatTime(date); // 今天
		} else if (inputTimestamp >= yesterdayTimestamp) {
			return `昨天${formatTime(date)}`; // 昨天
		} else if (inputTimestamp >= mondayTimestamp) {
			const weekDays = ['日', '一', '二', '三', '四', '五', '六'];
			return `星期${weekDays[date.getDay()]}`; // 本周内
		} else {
			return formatDate(date); // 更早时间
		}
	},
	/**
	 * title  标题
	 * type   类型：0只显示标，1显示加载图标，2显示成功图标，3显示失败图标 
	 * callBack  回调涵数
	 * s         回调涵数时间
	 */
	showToast(title,type=0,callBack=null,s=2000){
		if(!title) title=' ';
		title=title.toString();
		let icon='none';
		if(type == 1) icon='loading';
		else if(type == 2) icon='success';
		else if(type == 3) icon='error';
		uni.showToast({
			icon:icon,
			mask:true,
			title: title,
			duration: 2000,
			complete:()=>{
				setTimeout(()=>{
					typeof callBack == "function" && callBack();
				},s);
				
			}
		}); 
	},
	
    /**
	 * content  提示内容
	 * type   类型：0不显示取消按钮，1显示取消按钮
	 * callBack  回调涵数
	 */
	showModal(content,type=0,callBack=null){
		if(typeof content === 'object'){
			content=JSON.stringify(content);
		}else if(content){
			content=content.toString();
		} 
		let showCancel=false;
		if(type == 1) showCancel=true;
		uni.showModal({
			title: '温馨提示',
			content: content,
			showCancel:showCancel,
			success: (res)=> {
				if (res.confirm) {
					typeof callBack == "function" && callBack();
				} else if (res.cancel) {
					//console.log('用户点击取消');
				}
			}
		});
	},
	
	dataSetPage(e){
		let uri=e.currentTarget.dataset.uri;
		let type=e.currentTarget.dataset.type;
		if(!uri) {
			this.showToast('data-uri属性未设置跳转路径');
			return;
		}
		if(!type) type=0;
		this.goPage(uri,parseInt(type));
	},
	/**
	 * @param {Object} url 如果是数字并且小于 1 时返回当前数字的上N个页面，否则跳转对应路径
	 * @param {Object} type 
	 * type：0保留当前页面，跳转到应用内的某个页面，使用uni.navigateBack可以返回到原页面
	 * type：1关闭当前页面，跳转到应用内的某个页面
	 * type：2关闭所有页面，打开到应用内的某个页面
	 * type：3跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面
	 */
	goPage(url,type=0){
		if(!isNaN(url) && url < 1){
			url=parseInt(url.replace('-',url));
			uni.navigateBack({delta:url})
			return;
		}
		if(type == 0) {
			uni.navigateTo({url:url});
		}else if(type == 1){
			uni.redirectTo({url:url});
		}else if(type == 2){
			uni.reLaunch({url:url});
		}else if(type == 3){
			uni.switchTab({url:url});
		}
	},
	
	//获取上一页的路径
	getPrevPath(){
		let pages = getCurrentPages();  // 获取当前页面栈
		let prevPage = pages[pages.length - 2];  // 获取上一页实例
		let prevRoute = prevPage.route;  // 获取上一页路径
		return '/'+prevRoute;
	},
	
	//kb转换其它单位
	getFormatSize(size){
		let kb = 1024; // Kilobyte
		let mb = 1024 * kb; // Megabyte
		let gb = 1024 * mb; // Gigabyte
		let tb = 1024 * gb; // Terabyte
		if(size < kb){
			return size+"B";
		}else if(size < mb){
			return (size/kb).toFixed(1)+"KB";
		}else if(size < gb){
			return (size/mb).toFixed(1)+"MB";
		}else if(size < tb){
			return (size/gb).toFixed(1)+"GB";
		}else{
			return (size/tb).toFixed(1)+"TB";
		}
	},	
	/**
	 *获取用户位置
	 */
	getLocation(type='gcj02',geocode=true){
		return new Promise((rosolve,reject)=>{
			uni.getLocation({
				type:type,
				geocode:geocode,
				success:(data)=>{
					rosolve(data);
				},
				fail:(data)=>{
					reject(data);
				}
			});
		});
	},
	// 退出应用
	exitapply(){
		if (plus.os.name.toLowerCase() === 'android') {
			plus.runtime.quit(); // 安卓退出应用
			//console.log('安安卓');
		} else { 
			//console.log('ios');
			plus.ios.import('UIApplication').sharedApplication().performSelector('exit');  // iOS退出应用
		}
	},
	/**
	 * 获自定义 u-navbar 组件顶部安全距离
	 */
	getTopSecureRange(){
		let heightT=0;
		let systemInfo = uni.getSystemInfoSync();
		// #ifdef APP-PLUS || H5
		heightT=44
		// #endif
		// #ifdef MP
		heightT = systemInfo.platform == 'ios' ? 44 : 48;
		// #endif
		heightT+=systemInfo.statusBarHeight;
		return heightT;
	},
	/**
	 * 消息提醒
	 */
	audioObject:null,
	infoRemind(){
		if(!this.audioObject){
			let player = uni.createInnerAudioContext();
			player.loop=false;
			player.src ='/static/IPhone.mp3';
			this.audioObject=player;
			//console.log('infoRemind',1);
		}
		this.audioObject.stop();
		this.audioObject.play();
    },

	//过滤用户输入
	filterInput(str){
		let silter=(str,repStr)=>{
			str=str.replace(repStr, "");
			if(str.indexOf(repStr) > -1) return silter(str,repStr);
			return str;
		};
		let MAKR=uni.$appConfig['IM_PREFIX_MAKR'];
		MAKR.___SHOU_BAO_FEN_GE_FU___={rule:uni.$appConfig['RED_NUMBER']};
		for(let i in MAKR){
			str=silter(str,MAKR[i].rule);
		}
		return str;
	},
	//设置缓存
	setCache(key,value){
		if(value == null || value == ''){
			uni.setStorageSync(key, null);
			return;
		}
		let lcalData={
			time:parseInt(new Date().getTime() / 1000),
			data:value
		};
		uni.setStorageSync(key, lcalData);
		return lcalData;
	},
	//获取缓存
	getCache(key,second=0){
		let cache = uni.getStorageSync(key);
		if(!cache) return '';
		if(second == 0 || second == null || second == ''){
			return cache.data;
		}
		let time=parseInt(new Date().getTime() / 1000);
		if(time - cache.time > second) {
			uni.setStorageSync(key, null);
			return '';
		}
		return cache.data;
	},
	// 获取节点ID
	async getElementRect(id){
	  return new Promise(resolve => {
	    uni.createSelectorQuery()
	      .select('#'+id)
	      .boundingClientRect(res => {
	        resolve(res)
	      })
	      .exec()
	  })
	},
	//根据秒数解析出 00:00 这种格式
	formatSeconds(seconds) {
	    // 确保输入为有效数字
	    if (isNaN(seconds)) return '00:00';
	    seconds = Math.floor(Number(seconds));
	    // 计算分钟和秒数
	    const mins = Math.floor(seconds / 60);
	    const secs = seconds % 60;
	    // 格式化为两位数 (MM:SS)
	    return `${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
	},
	//随机头像
	getProfile(){
		let images=[];
		let k=0;
		for(let i=1;i<=9;i++) images[k++]='/static/profile/'+i+'.jpg';
		return images;
		/*let generateRandomArray=()=>{
			// 创建包含1-9的数组
			const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
			    // Fisher-Yates洗牌算法实现随机排序
			for (let i = arr.length - 1; i > 0; i--) {
			    const j = Math.floor(Math.random() * (i + 1));
			    [arr[i], arr[j]] = [arr[j], arr[i]]; // 交换元素
			}
			return arr;
		};
		let list=generateRandomArray();
		let fileList=[];
		for(let i=0;i<list.length;i++){
			fileList[fileList.length]='/static/profile/'+list[i]+'.jpg';
		}
		return fileList;*/
	}
}